import _ from 'lodash';
import {
  AllChannelsResponse,
  ArticlesResponse,
  Channel,
  ChannelListResponse,
} from '@/types/data';
import { RootThunkAction } from '@/types/store';
import { http } from '@/utils/http';
const CHANNEL_KEY = 'geek-channels';

// 获取频道数据
export const getUserChannel = (): RootThunkAction => {
  return async (dispatch, getState) => {
    const token = getState().login.token;
    // 1 用户登录
    if (token) {
      const res = await http.get<ChannelListResponse>('/user/channels');
      // console.log('pindao res', res.data.data.channels);
      dispatch({ type: '/home/getChannels', payload: res.data.data.channels });
    } else {
      // 2 用户未登录
      const localChannels = JSON.parse(
        localStorage.getItem(CHANNEL_KEY) || '[]'
      ) as Channel[];

      if (localChannels.length === 0) {
        // 获取默认频道列表
        const res = await http.get<ChannelListResponse>('/user/channels');
        // 保存到本地
        localStorage.setItem(
          CHANNEL_KEY,
          JSON.stringify(res.data.data.channels)
        );
        dispatch({
          type: '/home/getChannels',
          payload: res.data.data.channels,
        });
      } else {
        console.log('本地list', localChannels);
        dispatch({ type: '/home/getChannels', payload: localChannels });
      }
    }
  };
};

// 获取剩余频道
export const getRestChannel = (): RootThunkAction => {
  return async (dispatch, getState) => {
    // 获取所有频道
    const res = await http.get<AllChannelsResponse>('channels');
    const allChannels = res.data.data.channels;
    console.log('allChannels', allChannels);
    // 我的频道
    const myChannels = getState().home.channels;
    console.log('myChannels', myChannels);
    // 剩余频道
    // const restChannels = allChannels.filter(
    //   (item) => myChannels.findIndex((item2) => item.id === item2.id) < 0
    // );
    // 使用 lodash 第三方库
    const restChannels = _.differenceBy(allChannels, myChannels, 'id');

    console.log('restChannels', restChannels);

    // dispatch action
    dispatch({ type: '/home/getRestChannel', payload: restChannels });
  };
};

// 更新频道选中id
export const toggleChannel = (id: number): RootThunkAction => {
  return (dispatch) => {
    dispatch({ type: 'home/toggleChannel', payload: id });
  };
};

// 删除我的频道
export const delMyChannel = (channel: Channel): RootThunkAction => {
  return async (dispatch, getState) => {
    // 登录
    const token = getState().login.token;
    // const {login: {token}} = getState()
    if (token) {
      const res = await http.delete(`/user/channels/${channel.id}`);
      console.log('删除频道', res);
    } else {
      // 未登录
      // 1 取出来
      const localChannels = JSON.parse(
        localStorage.getItem(CHANNEL_KEY) || '[]'
      ) as Channel[];
      // 2 删除
      const userChannels = localChannels.filter(
        (item) => item.id !== channel.id
      );
      // 3 存储进去
      localStorage.setItem(CHANNEL_KEY, JSON.stringify(userChannels));
    }

    // 如果发生异常，就不会走这里的代码
    dispatch({ type: 'home/delMyChannel', payload: channel });
  };
};

// 添加频道
export const addChannel = (channel: Channel): RootThunkAction => {
  return async (dispatch, getState) => {
    const token = getState().login.token;
    // 登录
    if (token) {
      const res = await http.patch('/user/channels', { channels: [channel] });
      console.log('添加频道res', res);
    } else {
      // 未登录
      // 1 取处来
      const localChannels = JSON.parse(
        localStorage.getItem(CHANNEL_KEY) || '[]'
      ) as Channel[];
      // 2 添加
      // 用原生方法排序
      const userChannels = [...localChannels, channel].sort(
        (a, b) => a.id - b.id
      );
      // 3 存进去
      localStorage.setItem(CHANNEL_KEY, JSON.stringify(userChannels));
    }

    // 更新reducer数据
    dispatch({ type: 'home/addChannel', payload: channel });
  };
};

// 获取频道文章列表
export const getArticleList = (
  channelId: number,
  timestamp: number | string | null
): RootThunkAction => {
  return async (dispatch) => {
    const res = await http.get<ArticlesResponse>('/articles', {
      params: {
        channel_id: channelId,
        timestamp: timestamp,
      },
    });

    console.log('文章列表res', res.data.data);
    // console.log('文章列表res', res.data.data.pre_timestamp);
    // console.log('文章列表res', res.data.data.results);

    dispatch({
      type: 'home/getArticleList',
      payload: { channelId, articles: res.data.data },
    });
  };
};
